var createError = require('http-errors'); //错误信息
var express = require('express');
const formidable = require("formidable") //文件上传第三方模块
var multer = require('multer') //大文件切片上传
const code = require("svg-captcha"); //人机图片验证
const session = require("express-session"); //session模块
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var jwt = require("jsonwebtoken"); //token加密用包
var query = require("./db.js");
var bodyParser = require('body-parser');
var sm2 = require("./utils/sm2.js");

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

var errNum = 0;
var codeStr = 0;

app.all("*", function(req, res, next) {
	//设置允许跨域的域名，*代表允许任意域名跨域
	res.header("Access-Control-Allow-Origin", "*");
	//允许的header类型
	// res.header("Access-Control-Allow-Headers","content-type");
	res.header("Access-Control-Allow-Headers", "x-requested-with,Authorization,Content-Type");
	//跨域允许的请求方式 
	res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
	if (req.method.toLowerCase() == 'options')
		res.sendStatus(200); //让options尝试请求快速结束
	else
		next();
})
// bodyParser 用来解析post数据
app.use(bodyParser());
// app.use(express.static('public'));
// session中间件设置
app.use(session({
	secret: "webczc", // 对cookie进行签名
	name: "session", // cookie名称，默认为connect.sid
	resave: false, // 强制将会话保存回会话容器
	rolling: true, // 强制在每个response上设置会话标识符cookie
	cookie: {
		// 5分钟
		maxAge: 300000
	}
}))

function formatNumber(n) {
	n = n.toString()
	return n[1] ? n : '0' + n
}

function formatTimeTwo(number, format) {
	var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
	var returnArr = [];
	var date = new Date(number);
	returnArr.push(date.getFullYear());
	returnArr.push(formatNumber(date.getMonth() + 1));
	returnArr.push(formatNumber(date.getDate()));
	returnArr.push(formatNumber(date.getHours()));
	returnArr.push(formatNumber(date.getMinutes()));
	returnArr.push(formatNumber(date.getSeconds()));
	for (var i in returnArr) {
		format = format.replace(formateArr[i], returnArr[i]);
	}
	return format;
}
// 人机图片配置
function createCode() {
	return code.create({
		size: 4,
		ignoreChars: "0o1iIl",
		noise: 3,
		color: true,
		background: "#fff",
		fontSize: 60
	});
}
// 获取动态验证码
app.get('/api/code', function(req, res) {
	let code = createCode()
	res.type("svg")
	codeStr = code.text.toLowerCase()
	res.send(code.data);
})
// 登录管理员
app.get('/api/loginUser', function(req, res) {
	if (codeStr != req.query.code.toLowerCase()) {
		res.send({
			msg: '登录失败，验证码错误',
			code: 500,
			data: null
		});
		return false
	}
	query('SELECT * FROM user WHERE user_name = ?  OR user_phone= ? ', [req.query.username, req.query.username])
		.then(userArr => {
			if (userArr[0].is_clock == 1) {
				res.send({
					msg: '登录失败，账户被锁定',
					code: 500,
					data: docs
				});
				return false
			}
			if (userArr.length > 0) {
				query('SELECT * FROM user WHERE (user_name = ?  OR user_phone= ?  )AND user_password= ? ', [
					req.query.username, req.query.username, req.query.password
				]).then(docs => {
					console.log(errNum)
					if (docs.length > 0) {
						if (errNum >= 2) {
							res.send({
								msg: '登录失败，账户被锁定',
								code: 500,
								data: docs
							});
							//更改数据库里账户状态为锁定
							query('UPDATE user SET is_clock = ? WHERE user_name = ? ', [1, docs[0]
								.user_name
							]).then(result => {})
						} else {
							errNum = 0
							let content = {
								uname: docs[0].user_name
							}; // 要生成token的主题信息
							let secretOrPrivateKey = "suiyi" // 这是加密的key（密钥） 
							let token = jwt.sign(content, secretOrPrivateKey, {
								expiresIn: 60 * 60 * 24 // 24小时过期
							});
							//token写入数据库docs[0].token = token
							query('UPDATE user SET token = ? WHERE user_name = ? ', [token, docs[0]
								.user_name
							]).then(result => {
								res.send({
									msg: '登录成功，返回token~',
									code: 200,
									data: result,
									token: token
								});
							})
						}
					} else {
						if (errNum >= 2) {
							res.send({
								msg: '登录失败，账户被锁定',
								code: 500,
								data: docs
							});
							//更改数据库里账户状态为锁定
							query('UPDATE user SET is_clock = ? WHERE user_name = ? ', [1, req.query
								.username
							]).then(result => {})
						} else {
							errNum += 1;
							res.send({
								msg: '登录失败，密码错误',
								code: 500,
								data: docs
							});
						}
					}
				})
			} else {
				res.send({
					msg: '登录失败，未查询到用户',
					code: 500,
					data: userArr
				});
			}
		}).catch(error => {
			res.send({
				msg: '登录失败~',
				code: 500,
				data: error
			});
		})
});
// 退出登录 ，重置 用户token
app.get('/api/loginOut', function(req, res) {
	query('UPDATE admin SET token="" WHERE user_id = ?', [req.query.userid]).then(result => {
		res.send({
			msg: '退出成功~',
			code: 200,
			data: result
		});
	}).catch(error => {
		res.send({
			msg: '退出失败~',
			code: 500,
			data: error
		});
	})
});
// 文件上传
app.post("/api/upload/img", (request, response) => {
	const form = formidable({
		multiples: true,
		uploadDir: path.join(__dirname, "public/upload"),
		keepExtensions: true
	})
	form.parse(request, (err, fields, files) => {
		let res = fields
		// 说明上传了图片
		if (Object.keys(files).length > 0) {
			const basename = path.basename(files.file.path);
			const originUrl = request.headers.host
			// ${originUrl}
			const file_url = `${basename}`
			const fileObj = {
				url: file_url
			}
			res = {
				...res,
				...fileObj
			}
		}
		response.send(res)
	})
})

// 新增轮播图
app.post("/api/banner/add", (request, response) => {
	query('INSERT INTO banner (src,type) VALUES ( ? , ? )', [request.query.src, request.query.type]).then(
		result => {
			response.send({
				msg: '新增成功',
				code: 200,
				data: result
			});
		}).catch(error => {
		response.send({
			msg: '新增失败',
			code: 500,
			data: error
		});
	})
})

// 查询轮播图
app.get("/api/banner/list", (request, response) => {
	let param = request.query || req.params;
	let current_page = 1; //默认为1
	let size = 10; //每页条数
	let total = 0; //总条数 默认为零
	let type = '0'; //默认为查banner  0:banner 1:企业资质 2:企业文化
	if (param.type && param.type != '') {
		type = parseInt(param.type);
	}
	if (param.page) {
		current_page = parseInt(param.page);
	}
	if (param.size) {
		size = parseInt(param.size);
	}
	//查询数据总数
	query('SELECT count(*) FROM banner WHERE type = ?', [type]).then(result => {
		total = result[0]['count(*)']
		query(`SELECT * FROM banner WHERE type = ? limit ? offset ?`, [type, size, (current_page - 1) *
			size
		]).then(data => {
			response.send({
				msg: '获取banner成功',
				code: 200,
				data: {
					list: data,
					page: current_page,
					total: total,
					size: size
				}
			});
		}).catch(error => {
			response.send({
				msg: '获取banner失败',
				code: 500,
				data: error
			});
		})
	}).catch(error => {
		response.send({
			msg: '获取banner总数失败',
			code: 500,
			data: err
		});
	})
})

// 修改轮播图
app.post("/api/banner/change", (request, response) => {
	query('UPDATE banner SET src= ? , type= ? WHERE id= ? ', [request.query.src, request.query.type, request
		.query.id
	]).then(result => {
		response.send({
			msg: '编辑成功',
			code: 200,
			data: result
		});
	}).catch(error => {
		response.send({
			msg: '编辑失败',
			code: 500,
			data: error
		});
	})
})

// 删除轮播图
app.post("/api/banner/delete", (request, response) => {
	query('DELETE FROM banner WHERE id= ? ', [request.query.id]).then(result => {
		response.send({
			msg: '删除成功',
			code: 200,
			data: result
		});
	}).catch(error => {
		response.send({
			msg: '删除失败',
			code: 500,
			data: error
		});
	})
})

// 案例列表
app.get("/api/case/list", (request, response) => {
	var param = request.query || req.params;
	var current_page = 1; //默认为1
	var size = 10; //每页条数
	var total = 0; //总条数 默认为零
	if (param.page) {
		current_page = parseInt(param.page);
	}
	if (param.size) {
		size = parseInt(param.size);
	}
	//查询数据总数
	query('SELECT count(*) FROM `case`').then(result => {
		total = result[0]['count(*)']
		query('SELECT * FROM `case` ORDER BY update_time DESC limit ? offset ?', [size, (current_page -
			1) * size]).then(data => {
			response.send({
				msg: '获取案例成功',
				code: 200,
				data: {
					list: data,
					page: current_page,
					total: total,
					size: size
				}
			});
		}).catch(error => {
			response.send({
				msg: '获取案例失败',
				code: 500,
				data: error
			});
		})
	}).catch(error => {
		response.send({
			msg: '获取案例总数失败',
			code: 500,
			data: err
		});
	})
})
// 新增案例
app.post("/api/case/add", (request, response) => {
	query('INSERT INTO `case` (case_name,case_dec,case_con,case_src,creat_time,update_time) VALUES ( ? , ? , ? , ? , ? , ? )',
		[request.query.case_name, request.query.case_dec, request.query.case_con, request.query.case_src,
			formatTimeTwo(Date.parse(new Date()), 'Y-M-D h-m-s'), formatTimeTwo(Date.parse(new Date()),
				'Y-M-D h-m-s')
		]).then(result => {
		response.send({
			msg: '新增成功',
			code: 200,
			data: result
		});
	}).catch(error => {
		response.send({
			msg: '新增失败',
			code: 500,
			data: error
		});
	})
})
// 修改案例
app.post("/api/case/change", (request, response) => {
	query('UPDATE `case` SET case_name= ? , case_dec= ? , case_con= ? , case_src= ? update_time= ? WHERE id= ? ',
		[request.query.case_name, request.query.case_dec, request.query.case_con, request.query.case_src,
			formatTimeTwo(Date.parse(new Date()), 'Y-M-D h-m-s'), request.query.id
		]).then(result => {
		response.send({
			msg: '编辑成功',
			code: 200,
			data: result
		});
	}).catch(error => {
		response.send({
			msg: '编辑失败',
			code: 500,
			data: error
		});
	})
})
// 删除案例
app.post("/api/case/delete", (request, response) => {
	query('DELETE FROM `case` WHERE id= ? ', [request.query.id]).then(result => {
		response.send({
			msg: '删除成功',
			code: 200,
			data: result
		});
	}).catch(error => {
		response.send({
			msg: '删除失败',
			code: 500,
			data: error
		});
	})
})

// 招聘信息列表
app.get("/api/job/list", (request, response) => {
	var param = request.query || req.params;
	var current_page = 1; //默认为1
	var size = 10; //每页条数
	var total = 0; //总条数 默认为零
	if (param.page) {
		current_page = parseInt(param.page);
	}
	if (param.size) {
		size = parseInt(param.size);
	}
	//查询数据总数
	query('SELECT count(*) FROM job').then(result => {
		total = result[0]['count(*)']
		query('SELECT * FROM job ORDER BY update_time DESC limit ? offset ?', [size, (current_page -
			1) * size
		]).then(data => {
			let array = data.map((item) => {
				item.job_start = formatTimeTwo(Date.parse(item.job_start), 'Y-M-D');
				item.job_stop = formatTimeTwo(Date.parse(item.job_stop), 'Y-M-D');
				item.job_label = item.job_label.split(",");
				return item;
			})
			response.send({
				msg: '获取成功',
				code: 200,
				data: {
					list: array,
					page: current_page,
					total: total,
					size: size
				}
			});
		}).catch(error => {
			response.send({
				msg: '获取失败',
				code: 500,
				data: error
			});
		})
	}).catch(error => {
		response.send({
			msg: '获取总数失败',
			code: 500,
			data: err
		});
	})
})
// 新增招聘信息
app.post("/api/job/add", (request, response) => {
	query('INSERT INTO job (job_name,job_dec,job_need,job_label,job_start,job_stop,creat_time,update_time,is_start) VALUES ( ? , ? , ? , ? , ? , ? , ? , ? , ? )',
		[request.query.job_name, request.query.job_dec, request.query.job_need, request.query.job_label
			.toString(), request.query.job_start, request.query.job_stop, formatTimeTwo(Date.parse(
			new Date()), 'Y-M-D h-m-s'), formatTimeTwo(Date.parse(new Date()), 'Y-M-D h-m-s'), '1'
		]).then(result => {
		response.send({
			msg: '新增成功',
			code: 200,
			data: result
		});
	}).catch(error => {
		response.send({
			msg: '新增失败',
			code: 500,
			data: error
		});
	})
})
// 修改招聘信息
app.post("/api/job/change", (request, response) => {
	query('UPDATE job SET job_name= ? , job_dec= ? , job_need= ? , job_label= ? , job_start= ? , job_stop= ?, update_time= ? WHERE id= ? ',
		[request.query.job_name, request.query.job_dec, request.query.job_need, request.query.job_label
			.toString(), request.query.job_start, request.query.job_stop, formatTimeTwo(Date.parse(
			new Date()), 'Y-M-D h-m-s'), request.query.id
		]).then(result => {
		response.send({
			msg: '编辑成功',
			code: 200,
			data: result
		});
	}).catch(error => {
		response.send({
			msg: '编辑失败',
			code: 500,
			data: error
		});
	})
})
// 开启/关闭招聘
app.post("/api/job/isstart", (request, response) => {
	query('UPDATE job SET is_start= ?  WHERE id= ? ', [request.query.is_start, request.query.id]).then(
	result => {
		response.send({
			msg: '成功',
			code: 200,
			data: result
		});
	}).catch(error => {
		response.send({
			msg: '失败',
			code: 500,
			data: error
		});
	})
})
// 删除招聘信息
app.post("/api/job/delete", (request, response) => {
	query('DELETE FROM job WHERE id= ? ', [request.query.id]).then(result => {
		response.send({
			msg: '删除成功',
			code: 200,
			data: result
		});
	}).catch(error => {
		response.send({
			msg: '删除失败',
			code: 500,
			data: error
		});
	})
})
// 求职者信息列表
app.get("/api/recruitment/list", (request, response) => {
	var param = request.query || req.params;
	var current_page = 1; //默认为1
	var size = 10; //每页条数
	var total = 0; //总条数 默认为零
	if (param.page) {
		current_page = parseInt(param.page);
	}
	if (param.size) {
		size = parseInt(param.size);
	}
	//查询数据总数
	query('SELECT count(*) FROM seeker_info').then(result => {
		total = result[0]['count(*)']
		query('SELECT * FROM seeker_info ORDER BY update_time DESC limit ? offset ?', [size, (
			current_page - 1) * size]).then(data => {
			response.send({
				msg: '获取成功',
				code: 200,
				data: {
					list: data,
					page: current_page,
					total: total,
					size: size
				}
			});
		}).catch(error => {
			response.send({
				msg: '获取失败',
				code: 500,
				data: error
			});
		})
	}).catch(error => {
		response.send({
			msg: '获取总数失败',
			code: 500,
			data: err
		});
	})
})
// 新增求职者信息
app.post("/api/recruitment/add", (request, response) => {
	query('INSERT INTO seeker_info (seeker_job,seeker_name,seeker_talk,seeker_phone,seeker_email,creat_time) VALUES ( ? , ? , ? , ? , ? , ? )',
		[request.query.seeker_job, request.query.seeker_name, request.query.seeker_talk, request.query
			.seeker_phone, request.query.seeker_email, formatTimeTwo(Date.parse(new Date()), 'Y-M-D h-m-s'),
			'1'
		]).then(result => {
		response.send({
			msg: '新增成功',
			code: 200,
			data: result
		});
	}).catch(error => {
		response.send({
			msg: '新增失败',
			code: 500,
			data: error
		});
	})
})
// 修改求职者信息
app.post("/api/recruitment/change", (request, response) => {
	query('UPDATE seeker_info SET seeker_job= ? , seeker_name= ? , seeker_talk= ? , seeker_phone= ? , seeker_email= ?  WHERE id= ? ',
		[request.query.seeker_job, request.query.seeker_name, request.query.seeker_talk, request.query
			.seeker_phone, request.query.seeker_email, request.query.id
		]).then(result => {
		response.send({
			msg: '编辑成功',
			code: 200,
			data: result
		});
	}).catch(error => {
		response.send({
			msg: '编辑失败',
			code: 500,
			data: error
		});
	})
})
// 删除求职者信息
app.post("/api/recruitment/delete", (request, response) => {
	query('DELETE FROM seeker_info WHERE id= ? ', [request.query.id]).then(result => {
		response.send({
			msg: '删除成功',
			code: 200,
			data: result
		});
	}).catch(error => {
		response.send({
			msg: '删除失败',
			code: 500,
			data: error
		});
	})
})
// 新闻列表
app.get("/api/news/list", (request, response) => {
	var param = request.query || req.params;
	var type = ''; //默认为查所有 1资讯 2新闻
	var current_page = 1; //默认为1
	var size = 10; //每页条数
	var total = 0; //总条数 默认为零
	if (param.page) {
		current_page = parseInt(param.page);
	}
	if (param.size) {
		size = parseInt(param.size);
	}
	if (param.type && param.type != '') {
		type = parseInt(param.type);
	}
	//查询数据总数
	if (type == '') {
		query('SELECT count(*) FROM news').then(result => {
			total = result[0]['count(*)']
			query('SELECT * FROM news ORDER BY news_date DESC limit ? offset ?', [size, (current_page -
				1) * size]).then(data => {
				let array = data.map((item) => {
					item.news_date = formatTimeTwo(Date.parse(item.news_date),
						'Y-M-D h-m-s');
					return item;
				})
				response.send({
					msg: '获取成功',
					code: 200,
					data: {
						list: array,
						page: current_page,
						total: total,
						size: size
					}
				});
			}).catch(error => {
				response.send({
					msg: '获取失败',
					code: 500,
					data: error
				});
			})
		}).catch(error => {
			response.send({
				msg: '获取总数失败',
				code: 500,
				data: error
			});
		})
	} else {
		query('SELECT count(*) FROM news WHERE news_type = ?', [type]).then(result => {
			total = result[0]['count(*)']
			query('SELECT * FROM news WHERE news_type = ? ORDER BY news_date DESC limit ? offset ?', [
				type, size, (current_page - 1) * size
			]).then(data => {
				let array = data.map((item) => {
					item.news_date = formatTimeTwo(Date.parse(item.news_date),
						'Y-M-D h-m-s');
					return item;
				})
				response.send({
					msg: '获取成功',
					code: 200,
					data: {
						list: array,
						page: current_page,
						total: total,
						size: size
					}
				});
			}).catch(error => {
				response.send({
					msg: '获取失败',
					code: 500,
					data: error
				});
			})
		}).catch(error => {
			response.send({
				msg: '获取总数失败',
				code: 500,
				data: error
			});
		})
	}
})
// 新增新闻
app.post("/api/news/add", (request, response) => {
	query('INSERT INTO news (news_type,news_src,news_title,news_dec,news_url,news_date,news_writer) VALUES ( ? , ? , ? , ? , ? , ? , ? )',
		[request.query.news_type, request.query.news_src, request.query.news_title, request.query.news_dec,
			request.query.news_url, request.query.news_date, request.query.news_writer
		]).then(result => {
		response.send({
			msg: '新增成功',
			code: 200,
			data: result
		});
	}).catch(error => {
		response.send({
			msg: '新增失败',
			code: 500,
			data: error
		});
	})
})
// 修改新闻
app.post("/api/news/change", (request, response) => {
	query('UPDATE  news SET news_type= ? news_src= ? news_title= ? news_dec= ? news_url = ? news_date = ? news_writer= ? WHERE id= ?',
		[request.query.news_type, request.query.news_src, request.query.news_title, request.query.news_dec,
			request.query.news_url, request.query.news_date, request.query.news_writer, request.query.id
		]).then(result => {
		response.send({
			msg: '新增成功',
			code: 200,
			data: result
		});
	}).catch(error => {
		response.send({
			msg: '新增失败',
			code: 500,
			data: error
		});
	})
})
// 删除新闻
app.post("/api/news/delete", (request, response) => {
	query('DELETE FROM news WHERE id= ? ', [request.query.id]).then(result => {
		response.send({
			msg: '删除成功',
			code: 200,
			data: result
		});
	}).catch(error => {
		response.send({
			msg: '删除失败',
			code: 500,
			data: error
		});
	})
})
// 新增方案
app.post("/api/products/add", (request, response) => {
	query('INSERT INTO products (name,description,core_description,icon,image,type,creat_time) VALUES ( ? , ? , ? , ? , ? , ? , ? )',
		[request.body.name || '', request.body.description || '', request.body.core_description || '',
			request.body.icon || '', request.body.image || '', request.body.type || '', formatTimeTwo(Date
				.parse(new Date()), 'Y-M-D h-m-s')
		]).then(result => {
		response.send({
			msg: '新增成功',
			code: 200,
			data: result
		});
	}).catch(error => {
		response.send({
			msg: '新增失败',
			code: 500,
			data: error
		});
	})
})
// 新增技术手册
app.post("/api/products/file/add", (request, response) => {
	let arr = request.body.fileList.map(item => {
		item.push(formatTimeTwo(Date.parse(new Date()), 'Y-M-D h-m-s'))
		return item
	})
	if (arr.length > 0) {
		query('DELETE FROM products_files WHERE product_id= ? ', [arr[0][0]]).then(result => {}).catch(
		error => {})
	}
	// formatTimeTwo(Date.parse(new Date()), 'Y-M-D h-m-s')
	query('INSERT INTO products_files (name,url,product_id,creat_time) VALUES  ? ', [arr]).then(result => {
		response.send({
			msg: '新增成功',
			code: 200,
			data: result
		});
	}).catch(error => {
		response.send({
			msg: '新增失败',
			code: 500,
			data: error
		});
	})
})
// 查询技术手册
app.get("/api/products/file/list", (request, response) => {
	query('SELECT * FROM products_files WHERE product_id = ? ', [request.query.id]).then(data => {
		let array = data.map((item) => {
			item.creat_time = formatTimeTwo(Date.parse(item.creat_time), 'Y-M-D h-m-s');
			return item;
		})
		response.send({
			msg: '获取成功',
			code: 200,
			data: {
				list: array
			}
		});
	}).catch(error => {
		response.send({
			msg: '获取失败',
			code: 500,
			data: error
		});
	})
})
// 新增|编辑 功能/核心优势
app.post("/api/products/core/add", (request, response) => {
	let arr = request.body.coreList.map(item => {
		item.push(formatTimeTwo(Date.parse(new Date()), 'Y-M-D h-m-s'))
		return item
	})
	if (arr.length > 0) {
		query('DELETE FROM products_core WHERE product_id= ? ', [arr[0][0]]).then(result => {
			query('INSERT INTO products_core (product_id,img,title,description,type,creat_time) VALUES ? ',
				[arr]).then(result => {
				response.send({
					msg: '新增成功',
					code: 200,
					data: result
				});
			}).catch(error => {
				response.send({
					msg: '新增失败',
					code: 500,
					data: error
				});
			})
		}).catch(error => {})
	} else {
		query('INSERT INTO products_core (product_id,img,title,description,type,creat_time) VALUES ? ', [arr])
			.then(result => {
				response.send({
					msg: '新增成功',
					code: 200,
					data: result
				});
			}).catch(error => {
				response.send({
					msg: '新增失败',
					code: 500,
					data: error
				});
			})
	}
})
// 查询功能/核心优势
app.get("/api/products/core/list", (request, response) => {
	let id = ''
	if (request.query.id) {
		id = request.query.id
	}
	if (id == '') {
		query('SELECT * FROM products_core').then(data => {
			let array = data.map((item) => {
				item.creat_time = formatTimeTwo(Date.parse(item.creat_time), 'Y-M-D h-m-s');
				return item;
			})
			response.send({
				msg: '获取成功',
				code: 200,
				data: {
					list: array
				}
			});
		}).catch(error => {
			response.send({
				msg: '获取失败',
				code: 500,
				data: error
			});
		})
	} else {
		query('SELECT * FROM products_core WHERE product_id = ? ', [request.query.id]).then(data => {
			let array = data.map((item) => {
				item.creat_time = formatTimeTwo(Date.parse(item.creat_time), 'Y-M-D h-m-s');
				return item;
			})
			response.send({
				msg: '获取成功',
				code: 200,
				data: {
					list: array
				}
			});
		}).catch(error => {
			response.send({
				msg: '获取失败',
				code: 500,
				data: error
			});
		})
	}
})
// 方案列表
app.get("/api/products/list", (request, response) => {
	var param = request.query || req.params;
	var type = '0'; //默认为0：产品，1：解决方案，2：服务
	var current_page = 1; //默认为1
	var size = 10; //每页条数
	var total = 0; //总条数 默认为零
	if (param.page) {
		current_page = parseInt(param.page);
	}
	if (param.size) {
		size = parseInt(param.size);
	}
	if (param.type && param.type != '') {
		type = parseInt(param.type);
	}
	//查询数据总数
	query('SELECT count(*) FROM products_files').then(result => {
		total = result[0]['count(*)']
		query('SELECT * FROM products WHERE type = ? ORDER BY creat_time DESC limit ? offset ?', [type,
			size, (current_page - 1) * size
		]).then(data => {
			let array = data.map((item) => {
				item.creat_time = formatTimeTwo(Date.parse(item.creat_time),
					'Y-M-D h-m-s');
				return item;
			})
			response.send({
				msg: '获取成功',
				code: 200,
				data: {
					list: array,
					page: current_page,
					total: total,
					size: size
				}
			});
		}).catch(error => {
			response.send({
				msg: '获取失败',
				code: 500,
				data: error
			});
		})
	}).catch(error => {
		response.send({
			msg: '获取总数失败',
			code: 500,
			data: error
		});
	})
})
// 编辑方案
app.post("/api/products/change", (request, response) => {
	console.log(request.body.type)
	query('UPDATE products set name = ?, description = ?, core_description = ?, icon = ?, image = ?, type = ? WHERE id= ? ',
		[request.body.name || '', request.body.description || '', request.body.core_description || '',
			request.body.icon || '', request.body.image || '', request.body.type, request.body.id
		]).then(result => {
		console.log('编辑成功')
		response.send({
			msg: '编辑成功',
			code: 200,
			data: result
		});
	}).catch(error => {
		response.send({
			msg: '编辑失败',
			code: 500,
			data: error
		});
	})
})
// 删除方案
app.post("/api/products/delete", (request, response) => {
	query('DELETE FROM products WHERE id= ? ', [request.body.id]).then(result => {
		response.send({
			msg: '删除成功',
			code: 200,
			data: result
		});
	}).catch(error => {
		response.send({
			msg: '删除失败',
			code: 500,
			data: error
		});
	})
})
// 新增团队风采
app.post("/api/team/add", (request, response) => {
	query('INSERT INTO team (url,type,creat_time) VALUES ( ? , ? , ? )', [request.query.url, request.query.type,
		formatTimeTwo(Date.parse(new Date()), 'Y-M-D h-m-s')
	]).then(result => {
		response.send({
			msg: '新增成功',
			code: 200,
			data: result
		});
	}).catch(error => {
		response.send({
			msg: '新增失败',
			code: 500,
			data: error
		});
	})
})

// 查询团队风采
app.get("/api/team/list", (request, response) => {
	let param = request.query || req.params;
	let current_page = 1; //默认为1
	let size = 10; //每页条数
	let total = 0; //总条数 默认为零
	let type = '0'; //默认为查team  0:team 1:企业资质 2:企业文化
	if (param.type && param.type != '') {
		type = parseInt(param.type);
	}
	if (param.page) {
		current_page = parseInt(param.page);
	}
	if (param.size) {
		size = parseInt(param.size);
	}
	//查询数据总数
	query('SELECT count(*) FROM team WHERE type = ?', [type]).then(result => {
		total = result[0]['count(*)']
		query(`SELECT * FROM team WHERE type = ? ORDER BY creat_time DESC limit ? offset ?`, [type,
			size, (current_page - 1) * size
		]).then(data => {
			response.send({
				msg: '获取team成功',
				code: 200,
				data: {
					list: data,
					page: current_page,
					total: total,
					size: size
				}
			});
		}).catch(error => {
			response.send({
				msg: '获取team失败',
				code: 500,
				data: error
			});
		})
	}).catch(error => {
		response.send({
			msg: '获取team总数失败',
			code: 500,
			data: err
		});
	})
})

// 修改团队风采
app.post("/api/team/change", (request, response) => {
	query('UPDATE team SET url= ? , type= ? WHERE id= ? ', [request.query.url, request.query.type, request.query
		.id
	]).then(result => {
		response.send({
			msg: '编辑成功',
			code: 200,
			data: result
		});
	}).catch(error => {
		response.send({
			msg: '编辑失败',
			code: 500,
			data: error
		});
	})
})

// 删除团队风采
app.post("/api/team/delete", (request, response) => {
	query('DELETE FROM team WHERE id= ? ', [request.query.id]).then(result => {
		response.send({
			msg: '删除成功',
			code: 200,
			data: result
		});
	}).catch(error => {
		response.send({
			msg: '删除失败',
			code: 500,
			data: error
		});
	})
})

var server = app.listen(3001, function() {
	console.log("run......");
})

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
	extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
	next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
	// set locals, only providing error in development
	res.locals.message = err.message;
	res.locals.error = req.app.get('env') === 'development' ? err : {};

	// render the error page
	res.status(err.status || 500);
	res.render('error');
});

module.exports = app;
